package com.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.model.*;
import com.crm.mapper.CompanyMapper;
import com.crm.model.dto.CompanyDTO;
import com.crm.model.dto.ContactDTO;
import com.crm.model.query.CompanyQuery;
import com.crm.model.vo.*;
import com.crm.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.uilt.DateStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 公司 服务实现类
 * </p>
 *
 * @author zjd
 * @since 2021-04-01
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {


    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    private IContactService contactService;

    @Autowired
    private IDealService dealService;

    @Autowired
    private ITicketService ticketService;

    @Override
    @Transactional
    public Boolean deleteCompanyById(Long companyId) {
        Company company = baseMapper.selectById(companyId);
        if (company == null){
            return false;
        }
        //删除公司记录
        baseMapper.deleteById(companyId);
        //删除公司附件
        attachmentService.deleteByindexIdAndType(companyId, DateStatus.COMPANY.code);
        //删除公司联系人
        contactService.deleteCompanyContasct(companyId);
        //删除交易
        dealService.deleteCompanyDeal(companyId);
        //删除票证
        ticketService.deleteCompanyTicket(companyId);
        return true;
    }

    @Override
    @Transactional
    public Company addCompany(CompanyDTO dto) {
        Company company = BeanUtil.copyProperties(dto, Company.class);
        baseMapper.insert(company);
        return company;
    }

    @Override
    @Transactional
    public Boolean addCompanyAppertain(Long companyId,Long targetCompanyId, Integer type) {
        Company company = baseMapper.selectById(companyId);
        Company targetCompany = baseMapper.selectById(targetCompanyId);
        if (ObjectUtil.isEmpty(company) && ObjectUtil.isEmpty(targetCompany)){
            return false;
        }
        if (type==1){
            return addCompanyAppertainParent(company,targetCompanyId);
        }
        if (type==2){
            return addCompanyAppertainChild(targetCompany,companyId);
        }
        return false;
    }

    @Override
    public CompanyVO findCompanyInfoById(Long companyId) {
        Company company = baseMapper.selectById(companyId);
        if (ObjectUtil.isEmpty(company)){
            return new CompanyVO();
        }
        CompanyVO companyVO = BeanUtil.copyProperties(company, CompanyVO.class);
        //查询附件
        List<AttachmentVO> attachments = attachmentService.findByindexIdAndType(companyId, DateStatus.COMPANY.code);
        companyVO.setAttachmentVOList(attachments);
        //查询联系人
        List<ContactVO> contacts = contactService.findByindexIdAndType(companyId);
        companyVO.setContactVOList(contacts);
        //查询交易
        List<DealVO> deals = dealService.findByindexIdAndType(companyId);
        companyVO.setDealVOList(deals);
        //查询票证
        List<TicketVO> tickets = ticketService.findByindexIdAndType(companyId);
        companyVO.setTicketVOList(tickets);
        return companyVO;
    }

    @Override
    public Page<Company> listCompany(CompanyQuery companyQuery, Integer current, Integer size) {
        QueryWrapper wrapper = this.buildCompanyQueryWrapper(companyQuery);
        Page<Company> page = new Page<>(current,size);
        IPage<Company> companyPage = baseMapper.selectPage(page, wrapper);
        //List<Company> records = companyPage.getRecords();
        return (Page<Company>) companyPage;
    }

    @Override
    @Transactional
    public Company updateCompany(CompanyDTO dto) {
        Company entity = baseMapper.selectById(dto.getId());
        if (ObjectUtil.isEmpty(entity)){
            return null;
        }
        Company company = BeanUtil.copyProperties(dto, Company.class);
        company.setVersion(entity.getVersion());
        baseMapper.updateById(company);
        return company;
    }

    @Override
    @Transactional
    public Boolean addCompanyContact(ContactDTO dto) {
        Company entity = baseMapper.selectById(dto.getCompanyId());
        if (ObjectUtil.isEmpty(entity)){
            return false;
        }
        Contact contact = BeanUtil.copyProperties(dto, Contact.class);
        contactService.save(contact);
        return true;
    }

    @Override
    @Transactional
    public Boolean assignCompanyForUser(Long userId,Long companyId) {
        Company entity = baseMapper.selectById(companyId);
        if (ObjectUtil.isEmpty(entity)){
            return false;
        }
        entity.setOwnerUserId(userId);
        baseMapper.updateById(entity);
        return true;
    }

    @Override
    @Transactional
    public Boolean mergeCompany(Long targetCompanyId, Long companyId) {
        Company targetCompany = baseMapper.selectById(targetCompanyId);
        Company company = baseMapper.selectById(companyId);
        if (ObjectUtil.isEmpty(targetCompany) || ObjectUtil.isEmpty(company)){
            return false;
        }
        updateCompanyInfo(targetCompanyId, companyId);

        baseMapper.deleteById(targetCompanyId);
        return true;
    }

    @Override
    public Page<Company> listCompany(CompanyQuery companyQuery, Pageable pageable) {
        QueryWrapper wrapper = this.buildCompanyQueryWrapper(companyQuery);
        Page<Company> page = new Page<>(pageable.getPageNumber(),pageable.getPageSize());
        IPage<Company> companyPage = baseMapper.selectPage(page, wrapper);
        //List<Company> records = companyPage.getRecords();
        return (Page<Company>) companyPage;
    }

    /**
     * @Author zjd
     * @Description  查询目标公司下的联系人，交易，票证，附件 ，修改 关联公司
     * @Date 2021/4/2 9:35
     * @Param
     * @return
     */
    public void updateCompanyInfo(Long targetCompanyId,Long companyId){
        CompanyVO targetCompanyInfo = this.findCompanyInfoById(targetCompanyId);
        if (CollUtil.isNotEmpty(targetCompanyInfo.getContactVOList())){
            List<ContactVO> contactVOList = targetCompanyInfo.getContactVOList();
            List<Contact> contactList=new ArrayList<>();
            for (ContactVO contactVO : contactVOList ) {
                Contact contact = BeanUtil.copyProperties(contactVO, Contact.class);
                contact.setCompanyId(companyId);
                contactList.add(contact);
            }
            contactService.saveBatch(contactList);
        }
        if (CollUtil.isNotEmpty(targetCompanyInfo.getDealVOList())){
            List<DealVO> dealVOList = targetCompanyInfo.getDealVOList();
            List<Deal> dealList=new ArrayList<>();
            for (DealVO dealVO : dealVOList){
                Deal deal = BeanUtil.copyProperties(dealVO, Deal.class);
                deal.setCompanyId(companyId);
                dealList.add(deal);
            }
            dealService.saveBatch(dealList);
        }
        if (CollUtil.isNotEmpty(targetCompanyInfo.getTicketVOList())){
            List<TicketVO> ticketVOList = targetCompanyInfo.getTicketVOList();
            List<Ticket> ticketList=new ArrayList<>();
            for (TicketVO ticketVO : ticketVOList){
                Ticket ticket = BeanUtil.copyProperties(ticketVO, Ticket.class);
                ticket.setCompanyId(companyId);
                ticketList.add(ticket);
            }
            ticketService.saveBatch(ticketList);
        }
        if(CollUtil.isNotEmpty(targetCompanyInfo.getAttachmentVOList())){
            List<AttachmentVO> attachmentVOList = targetCompanyInfo.getAttachmentVOList();
            List<Attachment> attachmentList=new ArrayList<>();
            for (AttachmentVO attachmentVO: attachmentVOList) {
                Attachment attachment = BeanUtil.copyProperties(attachmentVO, Attachment.class);
                attachment.setIndexId(companyId);
                attachmentList.add(attachment);
            }
            attachmentService.saveBatch(attachmentList);
        }

    }

    public QueryWrapper buildCompanyQueryWrapper(CompanyQuery companyQuery){
        QueryWrapper<Company> wrapper = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(wrapper)){
            if (StrUtil.isNotEmpty(companyQuery.getName())){
                wrapper.like("name",companyQuery.getName());
            }
            if (StrUtil.isNotEmpty(companyQuery.getPhoneNumber())){
                wrapper.eq("phone_number",companyQuery.getPhoneNumber());
            }
            if (ObjectUtil.isNotEmpty(companyQuery.getOwnerUserId()) && companyQuery.getOwnerUserId()!=0L){
                wrapper.eq("owner_user_id",companyQuery.getOwnerUserId());
            }
        }
        wrapper.eq("is_delete",DateStatus.ONE.code);
        return wrapper;

    }


    public Boolean addCompanyAppertainParent(Company company,Long targetCompanyId){
        company.setParentCompanyId(targetCompanyId);
        baseMapper.updateById(company);
        return true;
    }

    public Boolean addCompanyAppertainChild(Company targetCompany,Long companyId){
        targetCompany.setParentCompanyId(companyId);
        baseMapper.updateById(targetCompany);
        return true;
    }

}
